package UploadAndDownload;

import Dao.UserDao;
import Dao.impl.UserDaoimpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class Upload extends HttpServlet {
    private UserDao  user = new UserDaoimpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //如何解释服务器发过来的内容？
//        1.数据第一步先判断上传的数据是否是多段（只有多段数据才是文件上传的）
        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            FileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

            try {
                //解析上传的数据，得到每一个表单项
                List <FileItem>list = servletFileUpload.parseRequest(req);
                //循环判断，每一个表单项是普通类型 还是上传的文件
                for (FileItem fileItem : list) {
                    if(fileItem.isFormField()){
                        //ture表示普通表单项
                           System.out.println("表单项的的name值："+fileItem.getFieldName());
                        //utf-8解决乱码问题
                        System.out.println("表单项的value属性值为:"+ fileItem.getString("GBK"));
                    }else{
                        //上传的文件

                        System.out.println("表单项的的name值："+fileItem.getFieldName());
                        System.out.println("上传的文件名为:"+ fileItem.getName());
                        fileItem.write(new File("F://"+fileItem.getName()));
                    }

                 }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
